from flask import Blueprint,request,render_template,session,redirect
from models.user import User
from models.history import History
from utils.errorMsg import errorResponse
from app import app
from db import db
ub = Blueprint('user',__name__,url_prefix='/user',template_folder='templates')

@ub.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        request.form = dict(request.form)

        def filter_fns(item):
            return request.form['username'] == item.user_name and request.form['password'] == item.user_password

        users = User.query.all()
        login_success = list(filter(filter_fns, users))
        if not len(login_success):
            return errorResponse('账号或密码错误')

        session['username'] = request.form['username']
        return redirect('/page/home', 301)

    else:
        return render_template('login.html')

@ub.route("/registry",methods=['GET','POST'])
def registry():
    if request.method == 'POST':
        request.form = dict(request.form)
        if request.form['password'] != request.form['passwordCheked']:
            return errorResponse('两次密码不符')
        else:
            def filter_fn(item):
                return request.form['username'] in item.user_name

            users = User.query.all()
            filter_list = list(filter(filter_fn, users))
            if len(filter_list):
                return errorResponse('该用户名已被注册')
            else:
                user = User(user_name=request.form['username'],user_password=request.form['password'])
                db.session.add(user)
                db.session.commit()

        session['username'] = request.form['username']
        return redirect('/user/login', 301)

    else:
        return render_template('register.html')

@ub.route("/logOut",methods=['GET','POST'])
def logOut():
    session.clear()
    return redirect('/user/login')